package service

import (
	"fmt"
	"gitee.com/jamon/espoir_go/common"
	"gitee.com/jamon/espoir_go/common/utils"
	"gitee.com/jamon/espoir_go/global"
)

type ReqPluginInterface interface {
	Start() error
	Stop() error
	HandleMsg(req *common.MsgRequest, res *common.MsgResponse) (err error)
	GetRouteInfo(req *common.MsgRequest) (routeGroupID uint32, subAddress uint32, err error)
}

type ReqBasePlugin struct {
	RouteGroupID uint32
	RouteMod     uint32
	PluginName   string

	MsgBaseID    uint32
	RequiredArgs []string
}

func (p *ReqBasePlugin) IsInMsgRange(msgID uint32) bool {
	return msgID/common.DefaultInnerMsgIDs.LenRange == p.MsgBaseID
}

func (p *ReqBasePlugin) GetUserID(sessionID string) (userID uint64, err error) {
	user, exist := global.GetUserManager().GetUserBySessionID(sessionID)
	if !exist {
		return 0, fmt.Errorf("user not exist, sessionID: %s", sessionID)
	}
	return user.UserID, nil
}

func (p *ReqBasePlugin) Response(status int, subResponse interface{}) *common.Response {
	return &common.Response{
		Code: status,
		Data: subResponse,
	}
}

var ReqPluginsMap utils.Map[uint32, *ReqPluginInterface] // msgBaseID -> plugin

func RegisterReqPlugin(msgBaseID uint32, plugin *ReqPluginInterface) (err error) {
	if ReqPluginsMap.IsNil() {
		ReqPluginsMap = utils.NewMap[uint32, *ReqPluginInterface]()
	}
	ReqPluginsMap.Put(msgBaseID, plugin)
	return
}
